var express = require("express");
var router = express.Router();
const { secretKey } = require("../utils/token");
const jwt = require("jsonwebtoken");
const multiparty = require("multiparty");
const path = require('path');

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express hello 测试云托管123123213" });
 
});

router.post("/upload", function (req, res) {
  var form = new multiparty.Form({ uploadDir: "./public/images" });
  form.parse(req, function (err, fields, files) {
    if (err) {
      res.send(err);
    } else {
      var p = files.file[0].path.substring(
        files.file[0].path.indexOf("images")
      );
      res.send({filename:path.basename(p)});
    }
  });
});

router.get('/getSession',function(req,res){
  // 从服务器获取session中的user对象，如果获取不到则返回空对象
  if(req.session.user){
    res.send(req.session.user);
  }else{
    res.send({});
  }
})
router.get('/removeSession',function(req,res){
  req.session.user = null;
  res.send({})
})
router.get('/getToken',function(req,res){
  // 获取到客户端发送过来的 token
  const token = req.get('Authorization');
  try{
    console.log(token);
    // 将编码后的 token 再转换回来
    const decode = jwt.verify(token.split(" ")[1], secretKey);
    res.send(decode);
  }catch(e){
    res.status(401).end();
  }
  
})

module.exports = router;
